package com.alice.controller;

import com.alice.entity.User;
import com.alice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/test")
    public void test(){
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        for (int i = 0; i < 10000; i++) {
            for (int j = 0; j < 20; j++) {
                User user = new User();
                user.setName("姓名"+i+j);
                user.setAge(i);
            }
        }
    }

    @GetMapping("gzip")
    public void gzip(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> userList = userService.list();
        response.setContentType("text/plain");
        String fileName = "userList";
        try {
            fileName = URLEncoder.encode("userList", "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".txt");
        BufferedOutputStream buff = null;
        StringBuffer write = new StringBuffer();
        String enter = "\r\n";
        ServletOutputStream outSTr = null;
        try {
            outSTr = response.getOutputStream(); // 建立
            buff = new BufferedOutputStream(outSTr);
            //把内容写入文件
            if (userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    write.append("id: "+ userList.get(i).getId() + ", ");
                    write.append("name: " + userList.get(i).getName() + ", ");
                    write.append("email: "+userList.get(i).getEmail() + ", ");
                    write.append("age: "+userList.get(i).getAge());
                    write.append(enter);
                }
            }
            buff.write(write.toString().getBytes("UTF-8"));
            buff.flush();
            buff.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buff.close();
                outSTr.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        StringBuilder s = new StringBuilder();
        
        String a="hello_world";
        a = a.replace("_"," ");
        System.out.printf(a);
    }
}
